package me.skyun.androidarch.common;

import android.graphics.Bitmap;
import android.util.Log;

import com.google.gson.Gson;

import java.io.DataOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by skyun on 17/8/23.
 */

public class DataOutputStreamEx extends DataOutputStream {
    /**
     * Creates a new data output stream to write data to the specified
     * underlying output stream. The counter <code>written</code> is
     * set to zero.
     *
     * @param out the underlying output stream, to be saved for later
     *            use.
     * @see FilterOutputStream#out
     */
    public DataOutputStreamEx(OutputStream out) {
        super(out);
    }

    public void writeString(String s) throws IOException {
        byte[] bytes = s.getBytes();
        writeInt(bytes.length);
        write(bytes);
    }

    public void writeBitmap(Bitmap bitmap) throws IOException {
        byte[] bytes = Utils.bitmap2Bytes(bitmap);
        writeInt(bytes.length);
        write(bytes);
    }

    public void writeObject(Object object) throws IOException {
        writeClass(object.getClass());
        writeString(new Gson().toJson(object));
    }

    public void writeList(List list) throws IOException {
        if (list == null || list.isEmpty()) {
            log("list is empty");
            return;
        }
        writeClass(list.get(0).getClass());
        writeString(new Gson().toJson(list));
    }

    public void writeEnum(Enum e) throws IOException {
        writeString(e.toString());
    }

    public void writeClass(Class cls) throws IOException {
        writeString(cls.getName());
    }

    private void log(String format, Object... args) {
        String log = String.format(format, args);
        Log.d(getClass().getName(), log);
    }
}
